package com.aiyige.base.db.table;

import android.os.Parcel;
import android.os.Parcelable;

import com.aiyige.model.moment.backup.CourseBackup;
import com.aiyige.model.moment.backup.TagBackup;
import com.aiyige.model.moment.entity.Guarantee;
import com.aiyige.model.moment.entity.Moment;
import com.aiyige.model.moment.entity.TrainingCard;
import com.aiyige.page.publish.coursedescription.model.CourseDescriptionModel;
import com.aiyige.page.publish.guarantee.model.GuaranteeItem;
import com.aiyige.page.publish.selectcourse.model.Course;
import com.aiyige.page.publish.selecttag.model.SelectTagItem;
import com.aiyige.page.publish.traingcard.model.TraingCardFormModel;
import com.aiyige.page.publish.util.PublishUtil;
import com.aiyige.setup.util.SetupUtil;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.j256.ormlite.field.DataType;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;

import java.util.LinkedList;
import java.util.List;

/**
 * Created by zhuyakun on 2017/12/14.
 */
@DatabaseTable(tableName = "TraingCardDBModel")
public class TraingCardDBModel implements Parcelable {
    public static final String ID_FIELD = "id";
    public static final String CONTROL_OPTION_FIELD = "controlOption";
    public static final String PROGRESS_STATUS_FIELD = "progressStatus";
    public static final String USER_ID_FIELD = "userId";
    public static final String GOODS_ID_FIELD = "goodsId";
    public static final String ROUTER_FIELD = "router";
    public static final String RETRY_COUNT_FIELD = "retryCount";
    public static final String GUARANTEE_FIELD = "guarantee";
    public static final String COURSE_FIELD = "course";
    @DatabaseField(id = true, columnName = ID_FIELD)
    String id;

    @DatabaseField(columnName = USER_ID_FIELD)
    String userId;

    @DatabaseField(columnName = GOODS_ID_FIELD)
    String goodsId;

    @DatabaseField
    String title;

    @DatabaseField
    int cardType;

    @DatabaseField
    String usageCount;

    @DatabaseField
    int effectiveType;

    @DatabaseField
    String validity;

    @DatabaseField
    String price;

    @DatabaseField
    String platformDividend;

    @DatabaseField(dataType = DataType.LONG_STRING)
    String tagJson;

    @DatabaseField(columnName = COURSE_FIELD, dataType = DataType.LONG_STRING)
    String course;

    @DatabaseField(dataType = DataType.LONG_STRING)
    String courseDesc;

    @DatabaseField
    String coverUrl;

    @DatabaseField
    String coverStoreKey;

    @DatabaseField
    boolean coverNeedUpload;

    @DatabaseField
    int publishOperationType;

    @DatabaseField(columnName = GUARANTEE_FIELD, dataType = DataType.LONG_STRING)
    String guarantee;

    @DatabaseField(columnName = PROGRESS_STATUS_FIELD)
    int progressStatus;

    @DatabaseField(columnName = CONTROL_OPTION_FIELD)
    int controlOption;

    @DatabaseField
    long releaseDate;

    @DatabaseField(columnName = ROUTER_FIELD)
    String router;

    @DatabaseField(columnName = RETRY_COUNT_FIELD)
    int retryCount;

    float uploadedPercent = 0f;

    String rejectReason;

    public TraingCardDBModel() {
    }

    private TraingCardDBModel(Builder builder) {
        setId(builder.id);
        setUserId(builder.userId);
        setGoodsId(builder.goodsId);
        setTitle(builder.title);
        setCardType(builder.cardType);
        setUsageCount(builder.usageCount);
        setEffectiveType(builder.effectiveType);
        setValidity(builder.validity);
        setPrice(builder.price);
        setPlatformDividend(builder.platformDividend);
        setTagJson(builder.tagJson);
        setCourse(builder.course);
        setCourseDesc(builder.courseDesc);
        setCoverUrl(builder.coverUrl);
        setCoverStoreKey(builder.coverStoreKey);
        setCoverNeedUpload(builder.coverNeedUpload);
        setPublishOperationType(builder.publishOperationType);
        setGuarantee(builder.guarantee);
        setProgressStatus(builder.progressStatus);
        setControlOption(builder.controlOption);
        setReleaseDate(builder.releaseDate);
        setRouter(builder.router);
        setRetryCount(builder.retryCount);
        setUploadedPercent(builder.uploadedPercent);
        setRejectReason(builder.rejectReason);
    }

    public static Builder newBuilder() {
        return new Builder();
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getGoodsId() {
        return goodsId;
    }

    public void setGoodsId(String goodsId) {
        this.goodsId = goodsId;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public int getCardType() {
        return cardType;
    }

    public void setCardType(int cardType) {
        this.cardType = cardType;
    }

    public String getUsageCount() {
        return usageCount;
    }

    public void setUsageCount(String usageCount) {
        this.usageCount = usageCount;
    }

    public int getEffectiveType() {
        return effectiveType;
    }

    public void setEffectiveType(int effectiveType) {
        this.effectiveType = effectiveType;
    }

    public String getValidity() {
        return validity;
    }

    public void setValidity(String validity) {
        this.validity = validity;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    public String getPlatformDividend() {
        return platformDividend;
    }

    public void setPlatformDividend(String platformDividend) {
        this.platformDividend = platformDividend;
    }

    public String getTagJson() {
        return tagJson;
    }

    public void setTagJson(String tagJson) {
        this.tagJson = tagJson;
    }

    public String getCourse() {
        return course;
    }

    public void setCourse(String course) {
        this.course = course;
    }

    public String getCourseDesc() {
        return courseDesc;
    }

    public void setCourseDesc(String courseDesc) {
        this.courseDesc = courseDesc;
    }

    public String getCoverUrl() {
        return coverUrl;
    }

    public void setCoverUrl(String coverUrl) {
        this.coverUrl = coverUrl;
    }

    public String getCoverStoreKey() {
        return coverStoreKey;
    }

    public void setCoverStoreKey(String coverStoreKey) {
        this.coverStoreKey = coverStoreKey;
    }

    public boolean isCoverNeedUpload() {
        return coverNeedUpload;
    }

    public void setCoverNeedUpload(boolean coverNeedUpload) {
        this.coverNeedUpload = coverNeedUpload;
    }

    public int getPublishOperationType() {
        return publishOperationType;
    }

    public void setPublishOperationType(int publishOperationType) {
        this.publishOperationType = publishOperationType;
    }

    public String getGuarantee() {
        return guarantee;
    }

    public void setGuarantee(String guarantee) {
        this.guarantee = guarantee;
    }

    public int getProgressStatus() {
        return progressStatus;
    }

    public void setProgressStatus(int progressStatus) {
        this.progressStatus = progressStatus;
    }

    public int getControlOption() {
        return controlOption;
    }

    public void setControlOption(int controlOption) {
        this.controlOption = controlOption;
    }

    public long getReleaseDate() {
        return releaseDate;
    }

    public void setReleaseDate(long releaseDate) {
        this.releaseDate = releaseDate;
    }

    public String getRouter() {
        return router;
    }

    public void setRouter(String router) {
        this.router = router;
    }

    public int getRetryCount() {
        return retryCount;
    }

    public void setRetryCount(int retryCount) {
        this.retryCount = retryCount;
    }

    public float getUploadedPercent() {
        return uploadedPercent;
    }

    public void setUploadedPercent(float uploadedPercent) {
        this.uploadedPercent = uploadedPercent;
    }

    public String getRejectReason() {
        return rejectReason;
    }

    public void setRejectReason(String rejectReason) {
        this.rejectReason = rejectReason;
    }

    public static final class Builder {
        private String id;
        private String userId;
        private String goodsId;
        private String title;
        private int cardType;
        private String usageCount;
        private int effectiveType;
        private String validity;
        private String price;
        private String platformDividend;
        private String tagJson;
        private String course;
        private String courseDesc;
        private String coverUrl;
        private String coverStoreKey;
        private boolean coverNeedUpload;
        private int publishOperationType;
        private String guarantee;
        private int progressStatus;
        private int controlOption;
        private long releaseDate;
        private String router;
        private int retryCount;
        private float uploadedPercent;
        private String rejectReason;

        private Builder() {
            id = "";
            goodsId = "";
        }

        public Builder id(String id) {
            this.id = id;
            return this;
        }

        public Builder userId(String userId) {
            this.userId = userId;
            return this;
        }

        public Builder goodsId(String goodsId) {
            this.goodsId = goodsId;
            return this;
        }

        public Builder title(String title) {
            this.title = title;
            return this;
        }

        public Builder cardType(int cardType) {
            this.cardType = cardType;
            return this;
        }

        public Builder usageCount(String usageCount) {
            this.usageCount = usageCount;
            return this;
        }

        public Builder effectiveType(int effectiveType) {
            this.effectiveType = effectiveType;
            return this;
        }

        public Builder validity(String validity) {
            this.validity = validity;
            return this;
        }

        public Builder price(String price) {
            this.price = price;
            return this;
        }

        public Builder platformDividend(String platformDividend) {
            this.platformDividend = platformDividend;
            return this;
        }

        public Builder tagJson(String tagJson) {
            this.tagJson = tagJson;
            return this;
        }

        public Builder course(String course) {
            this.course = course;
            return this;
        }

        public Builder courseDesc(String courseDesc) {
            this.courseDesc = courseDesc;
            return this;
        }

        public Builder coverUrl(String coverUrl) {
            this.coverUrl = coverUrl;
            return this;
        }

        public Builder coverStoreKey(String coverStoreKey) {
            this.coverStoreKey = coverStoreKey;
            return this;
        }

        public Builder coverNeedUpload(boolean coverNeedUpload) {
            this.coverNeedUpload = coverNeedUpload;
            return this;
        }

        public Builder publishOperationType(int publishOperationType) {
            this.publishOperationType = publishOperationType;
            return this;
        }

        public Builder guarantee(String guarantee) {
            this.guarantee = guarantee;
            return this;
        }

        public Builder progressStatus(int progressStatus) {
            this.progressStatus = progressStatus;
            return this;
        }

        public Builder controlOption(int controlOption) {
            this.controlOption = controlOption;
            return this;
        }

        public Builder releaseDate(long releaseDate) {
            this.releaseDate = releaseDate;
            return this;
        }

        public Builder router(String router) {
            this.router = router;
            return this;
        }

        public Builder retryCount(int retryCount) {
            this.retryCount = retryCount;
            return this;
        }

        public Builder uploadedPercent(float uploadedPercent) {
            this.uploadedPercent = uploadedPercent;
            return this;
        }

        public Builder rejectReason(String rejectReason) {
            this.rejectReason = rejectReason;
            return this;
        }

        public TraingCardDBModel build() {
            return new TraingCardDBModel(this);
        }
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(this.id);
        dest.writeString(this.userId);
        dest.writeString(this.goodsId);
        dest.writeString(this.title);
        dest.writeInt(this.cardType);
        dest.writeString(this.usageCount);
        dest.writeInt(this.effectiveType);
        dest.writeString(this.validity);
        dest.writeString(this.price);
        dest.writeString(this.platformDividend);
        dest.writeString(this.tagJson);
        dest.writeString(this.course);
        dest.writeString(this.courseDesc);
        dest.writeString(this.coverUrl);
        dest.writeString(this.coverStoreKey);
        dest.writeByte(this.coverNeedUpload ? (byte) 1 : (byte) 0);
        dest.writeInt(this.publishOperationType);
        dest.writeString(this.guarantee);
        dest.writeInt(this.progressStatus);
        dest.writeInt(this.controlOption);
        dest.writeLong(this.releaseDate);
        dest.writeString(this.router);
        dest.writeInt(this.retryCount);
        dest.writeFloat(this.uploadedPercent);
        dest.writeString(this.rejectReason);
    }

    protected TraingCardDBModel(Parcel in) {
        this.id = in.readString();
        this.userId = in.readString();
        this.goodsId = in.readString();
        this.title = in.readString();
        this.cardType = in.readInt();
        this.usageCount = in.readString();
        this.effectiveType = in.readInt();
        this.validity = in.readString();
        this.price = in.readString();
        this.platformDividend = in.readString();
        this.tagJson = in.readString();
        this.course = in.readString();
        this.courseDesc = in.readString();
        this.coverUrl = in.readString();
        this.coverStoreKey = in.readString();
        this.coverNeedUpload = in.readByte() != 0;
        this.publishOperationType = in.readInt();
        this.guarantee = in.readString();
        this.progressStatus = in.readInt();
        this.controlOption = in.readInt();
        this.releaseDate = in.readLong();
        this.router = in.readString();
        this.retryCount = in.readInt();
        this.uploadedPercent = in.readFloat();
        this.rejectReason = in.readString();
    }

    public static final Creator<TraingCardDBModel> CREATOR = new Creator<TraingCardDBModel>() {
        @Override
        public TraingCardDBModel createFromParcel(Parcel source) {
            return new TraingCardDBModel(source);
        }

        @Override
        public TraingCardDBModel[] newArray(int size) {
            return new TraingCardDBModel[size];
        }
    };

    public static TraingCardDBModel parse(Moment moment) {
        List<TagBackup> tagBackupList = moment.getTags();
        List<SelectTagItem> selectTagItemList = new LinkedList<>();
        for (TagBackup tagBackup : tagBackupList) {
            if (tagBackup == null) continue;
            switch (tagBackup.getGroupType()) {
                case SetupUtil.GROUP_TYPE_OTHER:
                    selectTagItemList.add(SelectTagItem.newBuilder()
                            .id(tagBackup.getId())
                            .name(tagBackup.getName())
                            .build());
                    break;
            }
        }
        List<GuaranteeItem> guaranteeItemList = new LinkedList<>();
        List<Guarantee> guaranteeList = moment.getDetailBackup().getGuarantee();
        for (Guarantee guarantee : guaranteeList) {
            guaranteeItemList.add(GuaranteeItem.newBuilder()
                    .id(guarantee.getId())
                    .title(guarantee.getName())
                    .content(guarantee.getDetail())
                    .build());
        }
        TrainingCard trainingCard = JSON.parseObject(moment.getMoreBackup(), TrainingCard.class);
        List<Course> courseList = new LinkedList<>();
        try {
            List<CourseBackup> courseBackupList = trainingCard.getBindCourseBackup();
            for (CourseBackup courseBackup : courseBackupList) {
                int courseType;
                switch (courseBackup.getSubject()) {
                    case Moment.SUBJECT_MAJOR_COURSE:
                        courseType = Course.TYPE_MAJOR_COURSE;
                        break;
                    case Moment.SUBJECT_TRAINING_COURSE:
                        courseType = Course.TYPE_TRAING_CLASS;
                        break;
                    default:
                        courseType = Course.TYPE_MAJOR_COURSE;
                        break;
                }
                courseList.add(Course.newBuilder()
                        .id(courseBackup.getId())
                        .type(courseType)
                        .title(courseBackup.getTitle())
                        .singlePrice(courseBackup.getBindUnitPrice() == null ? null : StringUtils.priceFormat(courseBackup.getBindUnitPrice()))
                        .courseNum(courseBackup.getClassCount() == null ? null : String.valueOf(courseBackup.getClassCount()))
                        .totalPrice(courseBackup.getPrice() == null ? null : StringUtils.priceFormat(courseBackup.getPrice()))
                        .build());
            }
        } catch (Exception e) {

        }

        CourseDescriptionModel courseDescriptionModel = CourseDescriptionModel.newBuilder().build();
        try {
            courseDescriptionModel.setCourseCoverList(PublishUtil.convertContentToCourseCover(trainingCard.getCoverSet()));
        } catch (Exception e) {

        }

        try {
            courseDescriptionModel.setArticleNodeList(PublishUtil.convertContentToArticle(moment.getDetailBackup().getContent()));
        } catch (Exception e) {

        }
        Integer cardType = null;
        try {
            switch (trainingCard.getCardType()) {
                case Moment.TRAINING_CARD_TYPE_TIME_CARD:
                    cardType = TraingCardFormModel.CARD_TYPE_TIME_CARD;
                    break;
                case Moment.TRAINING_CARD_TYPE_RECHARGEABLE_CARD:
                    cardType = TraingCardFormModel.CARD_TYPE_PREPAID_CARD;
                    break;
                case Moment.TRAINING_CARD_TYPE_MEASURED_CARD:
                    cardType = TraingCardFormModel.CARD_TYPE_COUNT_CARD;
                    break;
            }
        } catch (Exception e) {

        }
        Integer effectiveType = null;
        try {
            switch (trainingCard.getTakeEffectType()) {
                case Moment.TRAINING_CARD_TAKE_EFFECT_TYPE_ATTENDANCE:
                    effectiveType = TraingCardFormModel.EFFECTIVE_TYPE_ATTENDANCE;
                    break;
                case Moment.TRAINING_CARD_TAKE_EFFECT_TYPE_IMMEDIATE:
                    effectiveType = TraingCardFormModel.EFFECTIVE_TYPE_IMMEDIATE;
                    break;
            }
        } catch (Exception e) {

        }
        int progressStatus;
        switch (moment.getStatus()) {
            case Moment.STATUS_IN_REVIEW:
                progressStatus = PublishUtil.PROGRESS_STATUS_IN_REVIEW;
                break;
            case Moment.STATUS_REJECT:
                progressStatus = PublishUtil.PROGRESS_STATUS_REJECT;
                break;
            case Moment.STATUS_PUT_ON:
                progressStatus = PublishUtil.PROGRESS_STATUS_PUBLISHED;
                break;
            case Moment.STATUS_SAVE:
                progressStatus = PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED;
                break;
            case Moment.STATUS_REVIEW_PASSED:
                progressStatus = PublishUtil.PROGRESS_STATUS_PUBLISHED;
                break;
            case Moment.STATUS_GET_OFF:
                progressStatus = PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED;
                break;
            case Moment.STATUS_TRANSCODING:
                progressStatus=PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING;
                break;
            default:
                progressStatus = PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED;
                break;
        }


        return TraingCardDBModel.newBuilder()
                .userId(AccountUtil.getCurrentUser().getId())
                .goodsId(moment.getId())
                .title(moment.getTitle())
                .cardType(cardType)
                .usageCount(trainingCard.getUsageCount() == null ? null : String.valueOf(trainingCard.getUsageCount()))
                .effectiveType(effectiveType)
                .validity(trainingCard.getTakeEffectPeriod() == null ? null : String.valueOf(trainingCard.getTakeEffectPeriod()))
                .price(trainingCard.getPrice() == null ? null : StringUtils.priceFormat(trainingCard.getPrice()))
                .platformDividend(trainingCard.getDivisionProportion() == null ? StringUtils.priceFormat(PublishUtil.MIN_PLATFORM_DIVIDEND * 100) : StringUtils.priceFormat(trainingCard.getDivisionProportion() * 100))
                .tagJson(JSON.toJSONString(selectTagItemList))
                .course(JSON.toJSONString(courseList))
                .coverUrl(ListUtil.isEmpty(moment.getCover()) ? "" : moment.getCover().get(0))
                .coverNeedUpload(false)
                .progressStatus(progressStatus)
                .releaseDate(moment.getOnsellTime())
                .router(moment.getRouter())
                .rejectReason(moment.getRemark())
                .build();
    }
}
